package com.itheima.mall.intercepter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.mall.exception.ErrorResult;
import com.itheima.mall.vo.ResultData;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletResponse;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

//@RestControllerAdvice(basePackages = "com.itheima.ums.controller")
@RestControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice<Object> {
    @Autowired
    ObjectMapper objectMapper;
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        String[] urls = {"/product/getProductByIds"};
        List<String> uris = Arrays.stream(urls).collect(Collectors.toList());


        //判断来的响应是否需要处理
        String uri = request.getURI().getPath();
        if (uris.contains(uri)){
            return body;
        }

        if(body instanceof String){
            return objectMapper.writeValueAsString(ResultData.success(body));
        }
        // 防止二次封装
        if(body instanceof ResultData){
            return body;
        }

        if(body instanceof ErrorResult){
            return body;
        }
        return ResultData.success(body);
    }

}
